from flask import Blueprint, Flask, make_response
from flask_restplus import Api
from flask_cors import CORS
import json



def output_json(data, code, headers=None):
    """Makes a Flask response with a JSON encoded body"""
    resp = make_response(json.dumps(data), code)
    #if headers != None:
    #    headers['Access-Control-Allow-Origin'] = '*'
    #    headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
    #    headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type' 
    #    headers['Access-Control-Allow-Credentials'] = "true"
    resp.headers.extend(headers or {})

    return resp

class MyApi(Api):
    def __init__(self, *args, **kwargs):
        super(MyApi, self).__init__(*args, **kwargs)
        self.representations = {           
            'application/json': output_json
        }

def create_app():
    app = Flask(__name__)
    CORS(app, supports_credentials=True)
    # register api namespace
    register_api()

    # register blueprint
    from . import api_blueprint
    app.register_blueprint(api_blueprint)

    return app

def register_api():
    from .test.Apis import ns as user_api

    from . import api
    api.add_namespace(user_api)


api_blueprint = Blueprint("open_api", __name__, url_prefix="/api")
api = MyApi(api_blueprint, version="1.0",
          prefix="/v1", title="OpenApi", description="The Open Api Service")
    